from os import path
import os
import re
import urlparse
import urllib2
import libxml2
import libxslt
import sys

__all__ = ["transform", "parse"]

def replace(dir):
    os.chdir(dir)
    
    contents = os.listdir(dir)
    if 'previous' not in contents: os.mkdir('previous')
    for f in contents:
        if re.match('\w+.html$',f):
            print "writing %s"%f
            if f == 'menu.html': continue
            html = open(f).read()
            newhtml = transform(html,'insert_menu.xsl')
            #newhtml = 'foo'

            oldfile = open(os.path.join('previous',f),'w')
            oldfile.write(html)
            oldfile.close()
            
            newfile = open(f+'.test.html','w')
            #newfile = open(f,'w')
            newfile.write(newhtml)
            newfile.close()

            print "rewritten %s"%f
        
         
def stylesheet(filename):
    styledoc = libxml2.parseFile(filename)
    style = libxslt.parseStylesheetDoc(styledoc)
    return style

libxslt.registerAllExtras()

def transform(xml, style, format=False):
    
#fp = urllib2.urlopen(uri)
#    data = fp.read()
#    fp.close()
    data = xml
    doc = libxml2.parseDoc(data)
    style = stylesheet(style)
    libxslt.registerAllExtras()
    result = style.applyStylesheet(doc,{})
     
    rdfxml = result.serialize("utf-8", format)

    style.freeStylesheet()
    result.freeDoc()
    doc.freeDoc()

    return rdfxml

if __name__ == '__main__':
#    import doctest
#    doctest.testmod()
    replace(os.getcwd())
    #transform(sys.argv[1],sys.argv[2])
